package com.course.business.controller.web.discusspost;

import com.course.business.controller.web.discusspost.event.EventProducer;
import com.course.server.domain.Member;
import com.course.server.domain.discusspost.Event;
import com.course.server.dto.ResponseDto;
import com.course.server.service.discusspost.LikeService;
import com.course.server.util.CommunityConstant;
import com.course.server.util.HostHolder;
import com.course.server.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/web")
public class LikeController implements CommunityConstant {

    @Autowired
    private LikeService likeService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private EventProducer eventProducer;

    @Resource(name="myRedisTemplate")
    private RedisTemplate redisTemplate;

    @RequestMapping(path = "/like", method = RequestMethod.POST)
    public ResponseDto like(@RequestBody Map<String,String> map) {

        String entityType=map.get("entityType");
        String entityId=map.get("entityId");
        String entityUserId=map.get("entityUserId");
        String postId=map.get("postId");

        Member user = hostHolder.getMember();

        // 点赞
        likeService.like(user.getId(), entityType, entityId, entityUserId);

        // 数量
        long likeCount = likeService.findEntityLikeCount(entityType, entityId);
        // 状态
        int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);
        // 返回的结果
        Map<String, Object> dto = new HashMap<>();
        dto.put("likeCount", likeCount);
        dto.put("likeStatus", likeStatus);

        // 触发点赞事件
        if (likeStatus == 1) {
            Event event = new Event()
                    .setTopic(TOPIC_LIKE)
                    .setUserId(hostHolder.getMember().getId())
                    .setEntityType(entityType)
                    .setEntityId(entityId)
                    .setEntityUserId(entityUserId)
                    .setData("postId", postId);
            eventProducer.fireEvent(event);
        }

        if(entityType.equals(ENTITY_TYPE_POST)) {
            // 计算帖子分数
            String redisKey = RedisKeyUtil.getPostScoreKey();
            redisTemplate.opsForSet().add(redisKey, postId);
        }

        ResponseDto responseDto=new ResponseDto();
        responseDto.setContent(dto);
        return responseDto;
    }

}
